package com.chris.common.utils;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MinioUtils {

    @Autowired
    private MinioClient minioClient;


    /**
     * 创建桶
     *
     * @param bucketName
     * @throws IOException
     * @throws InvalidKeyException
     * @throws InvalidResponseException
     * @throws InsufficientDataException
     * @throws NoSuchAlgorithmException
     * @throws ServerException
     * @throws InternalException
     * @throws XmlParserException
     * @throws ErrorResponseException
     */
    private void createBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        if (!minioClient.bucketExists(new BucketExistsArgs.Builder().bucket(bucketName).build())) {
            minioClient.makeBucket(new MakeBucketArgs.Builder().bucket(bucketName).build());
        }
    }


    public String upload(String bucketName, String fileName, InputStream inputStream) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InsufficientDataException, InternalException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        createBucket(bucketName);
        String suf = fileName.substring(fileName.lastIndexOf("."));
        PutObjectArgs.Builder builder = new PutObjectArgs.Builder();
        fileName = System.currentTimeMillis() + suf;
        String bucketObject=simpleDateFormat.format(new Date()) + "/" + fileName;
        builder.bucket(bucketName)
                .object(bucketObject)
                .stream(inputStream, inputStream.available(), -1);
        minioClient.putObject(builder.build());
        //获取访问图片的路径
        return minioClient.getPresignedObjectUrl(new GetPresignedObjectUrlArgs.Builder()
                .bucket(bucketName)
                .object(bucketObject)
                .method(Method.GET)
//                .expiry(1, TimeUnit.DAYS)
                .build());

    }


}
